package com.cskaoyan.utils;
/*
 * @Auther:王贲
 * @Date:2022/9/9
 * @Description:
 * @VERSON:1.8
 */

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.exception.ValidatorException;
import lombok.SneakyThrows;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

public class HibernateValidatorUtils {

    @SneakyThrows
    public static BaseRespVo getBaseRespVo(BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {//查看校验是否通过，否返回ture
            //拿到错误的校验信息
            FieldError fieldError = bindingResult.getFieldError();
            String field = fieldError.getField();// 成员变量名
            Object rejectedValue = fieldError.getRejectedValue();//错误的值
            String defaultMessage = fieldError.getDefaultMessage();//错误的信息
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("请求参数").append(field).append("传入了错误的值").append(rejectedValue).append(":").append(defaultMessage);
            return BaseRespVo.invalidParam(stringBuffer.toString());
        }
        return null;
    }

    @SneakyThrows
    public static void valid(BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {//查看校验是否通过，否返回ture
            //拿到错误的校验信息
            FieldError fieldError = bindingResult.getFieldError();
            String field = fieldError.getField();// 成员变量名
            Object rejectedValue = fieldError.getRejectedValue();//错误的值
            String defaultMessage = fieldError.getDefaultMessage();//错误的信息
            StringBuffer stringBuffer = new StringBuffer();
            // stringBuffer.append("请求参数").append(field).append("传入了错误的值").append(rejectedValue).append(":").append(defaultMessage);
            String msg = "";
            throw new ValidatorException(msg);
        }
    }
}
